package com.service.component.common.utils;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.service.component.user.entity.Users;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.util.Date;

@Component
public class CommonMetaObjectHandler implements MetaObjectHandler {

    /**
     * 插入时的填充策略
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Subject subject = SecurityUtils.getSubject();
        Users user = ObjectUtils.isNotEmpty(subject.getPrincipals()) ? subject.getPrincipals().oneByType(Users.class) : new Users();
        this.setFieldValByName("createTime", new Timestamp(new Date().getTime()), metaObject);
        this.setFieldValByName("creatoNo", user.getCreatoNo(), metaObject);
        this.setFieldValByName("updateTime", new Timestamp(new Date().getTime()), metaObject);
        this.setFieldValByName("modifierNo", user.getModifierNo(), metaObject);
    }

    /**
     * 更新时的填充策略
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        Subject subject = SecurityUtils.getSubject();
        Users user = ObjectUtils.isNotEmpty(subject.getPrincipals()) ? subject.getPrincipals().oneByType(Users.class) : new Users();
        this.setFieldValByName("updateTime", new Timestamp(new Date().getTime()), metaObject);
        this.setFieldValByName("modifierNo", user.getModifierNo(), metaObject);
    }
}